#!/usr/bin/env python
"""
安全配置管理器命令行接口
提供多语言接口访问能力
"""

import argparse
import json
import sys
import os
import logging
from typing import Dict, Any, Optional
from cryptography.fernet import InvalidToken

# 导入核心组件
from .core.config_manager import SecureConfigManager
from .core.encryption import EnhancedAES256Encryptor
from .core.keychain import SystemKeychain

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stderr) # Log to stderr
    ]
)
logger = logging.getLogger("secure_config_cli")

def get_encryptor() -> Optional[EnhancedAES256Encryptor]:
    """获取当前的加密器实例"""
    try:
        master_key = SystemKeychain.get_master_key()
        if not master_key:
            # Log to stderr, which is the default for logging,
            # but also return specific error structure for CLI output
            logger.error("无法获取主密钥，请确保环境变量 SECURECONFIGMASTERKEY 已设置")
            return None
        return EnhancedAES256Encryptor(master_key)
    except Exception as e:
        logger.error(f"获取加密器失败: {e}")
        return None

def output_result(result: Dict[str, Any], output_format: str = "json") -> None:
    """输出结果到标准输出 (stdout)"""
    if output_format == "json":
        print(json.dumps(result, ensure_ascii=False, indent=4)) # Use indent for readability
    else: # Text format
        for key, value in result.items():
            if isinstance(value, list):
                print(f"{key}:")
                for item in value:
                    print(f"  - {item}")
            elif isinstance(value, dict):
                print(f"{key}:")
                for sub_key, sub_value in value.items():
                    print(f"  {sub_key}: {sub_value}")
            else:
                print(f"{key}: {value}")

# --- Command Implementations ---

def cmd_list_configs(args, manager: SecureConfigManager):
    """列出所有配置文件"""
    try:
        configs = manager.list_configs(file_type=args.type)
        result = {
            "status": "success",
            "configs": configs,
            "count": len(configs)
        }
        return result, 0
    except Exception as e:
        logger.error(f"列出配置文件失败: {e}", exc_info=args.verbose)
        return {"status": "error", "message": f"列出配置文件失败: {e}"}, 1

def cmd_get_config(args, manager: SecureConfigManager):
    """获取配置文件内容"""
    try:
        encryptor = None
        if not args.raw:
            encryptor = get_encryptor()
            if not encryptor:
                return {"status": "error", "message": "无法获取主密钥，无法解密配置"}, 1

        # 获取配置数据
        if args.raw:
            data = manager.get_file_data(args.name, file_type=args.type)
        else:
            data = manager.get_decrypted_file_content(args.name, encryptor, file_type=args.type)

        if data is None:
            # Check if file exists at all to differentiate
            if not manager.file_exists(args.name, file_type=args.type):
                return {"status": "error", "message": f"文件 '{args.name}' 不存在"}, 1
            else:
                # Exists but failed to decrypt or empty after decryption attempt
                return {"status": "error", "message": f"无法获取或解密文件 '{args.name}' 的内容"}, 1

        result = {
            "status": "success",
            "name": args.name,
            "raw_request": args.raw,
            "type": args.type,
            "data": data
        }
        return result, 0
    except Exception as e:
        logger.error(f"获取文件 '{args.name}' 失败: {e}", exc_info=args.verbose)
        return {"status": "error", "message": f"获取文件失败: {e}"}, 1

def cmd_get_value(args, manager: SecureConfigManager):
    """获取配置中的特定值"""
    try:
        # 只允许 json 类型
        if hasattr(args, 'type') and args.type != "json":
            return {"status": "error", "message": "get-value 命令仅支持 json 类型文件。"}, 1
        encryptor = get_encryptor()
        if not encryptor:
            return {"status": "error", "message": "无法获取主密钥，无法解密配置"}, 1

        # 解析键路径
        key_path = args.key_path.split('.')
        if not key_path or not all(key_path): # Ensure path is not empty and has no empty segments
            return {"status": "error", "message": "无效的键路径"}, 1

        # 获取解密后的数据
        data = manager.get_decrypted_file_content(args.name, encryptor, file_type="json")
        if data is None:
            if not manager.config_exists(args.name):
                return {"status": "error", "message": f"配置文件 '{args.name}' 不存在"}, 1
            else:
                return {"status": "error", "message": f"无法获取或解密配置文件 '{args.name}'"}, 1

        # 在数据中查找值
        current = data
        for key in key_path:
            if not isinstance(current, dict) or key not in current:
                return {"status": "error", "message": f"键路径 '{args.key_path}' 在配置文件 '{args.name}' 中不存在"}, 1
            current = current[key]

        result = {
            "status": "success",
            "name": args.name,
            "key_path": args.key_path,
            "value": current
        }
        return result, 0
    except Exception as e:
        logger.error(f"获取配置值 '{args.key_path}' 从 '{args.name}' 失败: {e}", exc_info=args.verbose)
        return {"status": "error", "message": f"获取配置值失败: {e}"}, 1

def cmd_set_value(args, manager: SecureConfigManager):
    """设置配置中的特定值"""
    try:
        # 只允许 json 类型
        if hasattr(args, 'type') and args.type != "json":
            return {"status": "error", "message": "set-value 命令仅支持 json 类型文件。"}, 1
        encryptor = get_encryptor()
        if not encryptor:
            return {"status": "error", "message": "无法获取主密钥，无法加密配置"}, 1

        # 解析键路径
        key_path = args.key_path.split('.')
        if not key_path or not all(key_path):
            return {"status": "error", "message": "无效的键路径"}, 1

        # 获取解密后的数据或创建新数据
        data = manager.get_decrypted_file_content(args.name, encryptor, file_type="json")
        if data is None:
            if manager.config_exists(args.name):
                return {"status": "error", "message": f"无法解密现有配置文件 '{args.name}' 以设置值"}, 1
            else:
                data = {} # Start fresh for a new file

        # 解析值（尝试JSON解析，失败则作为字符串处理）
        try:
            if args.value.isdigit():
                value = int(args.value)
            elif args.value.replace('.', '', 1).isdigit():
                 value = float(args.value)
            elif args.value.lower() in ['true', 'false']:
                 value = args.value.lower() == 'true'
            else:
                try:
                    value = json.loads(args.value)
                except json.JSONDecodeError:
                    value = args.value
        except Exception as e:
            logger.warning(f"解析输入值 '{args.value}' 时出错，将作为字符串处理: {e}")
            value = args.value

        # 在数据中构建路径并设置值
        current = data
        for i, key in enumerate(key_path[:-1]):
            if key not in current or not isinstance(current.get(key), dict):
                current[key] = {}
            current = current[key]

        # 设置最终值
        last_key = key_path[-1]
        current[last_key] = value

        # 保存加密后的数据
        manager.encrypt_and_save_content(args.name, data, encryptor, file_type="json")

        result = {
            "status": "success",
            "name": args.name,
            "key_path": args.key_path,
            "message": "值已成功设置"
        }
        return result, 0
    except Exception as e:
        logger.error(f"设置配置值 '{args.key_path}' 到 '{args.name}' 失败: {e}", exc_info=args.verbose)
        return {"status": "error", "message": f"设置配置值失败: {e}"}, 1

def cmd_create_config(args, manager: SecureConfigManager):
    """创建新的配置文件"""
    try:
        encryptor = get_encryptor()
        if not encryptor:
            return {"status": "error", "message": "无法获取主密钥，无法加密配置"}, 1

        # 检查文件是否已存在
        if manager.file_exists(args.name, file_type=args.type) and not args.force:
            return {"status": "error", "message": f"文件 '{args.name}' 已存在，使用 --force 覆盖"}, 1

        # 创建初始数据
        data = None
        if args.template:
            if args.template == "empty":
                data = None # 由 create_file 内部根据类型自动赋默认值
            elif args.template == "basic" and args.type == "json":
                data = {
                    "app": {
                        "name": "MyApp",
                        "version": "1.0.0"
                    },
                    "database": {
                        "host": "localhost",
                        "port": 5432,
                        "username": "user",
                        "password": "secure_password_placeholder"
                    }
                }
            else:
                return {"status": "error", "message": f"未知的模板: {args.template} 或该模板不支持此类型"}, 1

        # 保存加密后的数据
        manager.create_file(args.name, file_type=args.type, initial_data=data, encrypt=True, force=args.force, encryptor=encryptor)

        result = {
            "status": "success",
            "name": args.name,
            "type": args.type,
            "message": f"文件 '{args.name}' 已创建" + (f" (使用模板: {args.template})" if args.template else "")
        }
        return result, 0
    except Exception as e:
        logger.error(f"创建文件 '{args.name}' 失败: {e}", exc_info=args.verbose)
        return {"status": "error", "message": f"创建文件失败: {e}"}, 1

def cmd_delete_config(args, manager: SecureConfigManager):
    """删除配置文件"""
    try:
        if not manager.file_exists(args.name, file_type=args.type):
             return {"status": "error", "message": f"文件 '{args.name}' 不存在"}, 1

        # Attempt deletion
        deleted = manager.delete_file(args.name, file_type=args.type)

        if deleted:
            result = {
                "status": "success",
                "name": args.name,
                "type": args.type,
                "message": f"文件 '{args.name}' 已删除"
            }
            return result, 0
        else:
            # Deletion might fail due to permissions or other issues
            return {"status": "error", "message": f"删除文件 '{args.name}' 失败 (可能是权限问题?)"}, 1

    except Exception as e:
        logger.error(f"删除文件 '{args.name}' 失败: {e}", exc_info=args.verbose)
        return {"status": "error", "message": f"删除文件时发生错误: {e}"}, 1

def cmd_encrypt_plaintext(args, manager: SecureConfigManager):
    """加密明文文件"""
    try:
        encryptor = get_encryptor()
        if not encryptor:
             return {"status": "error", "message": "无法获取主密钥，无法加密文件"}, 1

        files_to_process = []
        if args.name:
             files_to_process = [args.name]
        else:
             configs = manager.list_configs(file_type=args.type)
             files_to_process = [c["name"] for c in configs]

        success_files = []
        error_files = []
        skipped_files = []

        for filename in files_to_process:
            try:
                raw_data = manager.get_file_data(filename, file_type=args.type)
                if raw_data is None:
                    logger.warning(f"无法读取文件 '{filename}' 或文件为空，跳过加密。")
                    error_files.append(f"{filename} (无法读取)")
                    continue
                # Encrypt and save (overwrites the existing file)
                manager.encrypt_and_save_content(filename, raw_data, encryptor, file_type=args.type, inplace=args.inplace)
                success_files.append(filename)
            except Exception as e:
                logger.error(f"加密文件 '{filename}' 失败: {e}", exc_info=args.verbose)
                error_files.append(f"{filename} ({e})")

        message = f"加密操作完成. 成功: {len(success_files)}, 失败: {len(error_files)}."
        result = {
            "status": "success" if not error_files else "partial_error",
            "success_files": success_files,
            "error_files": error_files,
            "message": message
        }
        return result, (1 if error_files else 0)

    except Exception as e:
        logger.error(f"加密明文文件失败: {e}", exc_info=args.verbose)
        return {"status": "error", "message": f"加密操作失败: {e}"}, 1


def cmd_decrypt_to_plaintext(args, manager: SecureConfigManager):
    """解密文件为明文"""
    if args.inplace:
        logger.warning("原地解密操作将直接覆盖加密文件，不改变文件名。请谨慎操作或先备份。")
    else:
        logger.warning("解密操作将创建明文文件并删除加密文件。请谨慎操作或先备份。")
    try:
        encryptor = get_encryptor()
        if not encryptor:
            return {"status": "error", "message": "无法获取主密钥，无法解密文件"}, 1

        files_to_process = []
        if args.name:
             if not manager.file_exists(args.name, file_type=args.type):
                 return {"status": "error", "message": f"文件 '{args.name}' 不存在"}, 1
             files_to_process = [args.name]
        else:
             configs = manager.list_configs(file_type=args.type)
             files_to_process = [c["name"] for c in configs]
             if not files_to_process:
                 return {"status": "info", "message": "没有找到要解密的文件"}, 0

        success_files = []
        error_files = []

        for filename in files_to_process:
            try:
                # --- 1. 确定要读取的源加密文件路径 --- 
                source_path_to_decrypt = None
                encrypted_bytes = None
                
                encrypted_path_default = manager._get_path(filename, file_type=args.type, encrypted=True)
                potential_inplace_source_path = manager._get_path(filename, file_type=args.type, encrypted=False)
                
                if encrypted_path_default.exists():
                    source_path_to_decrypt = encrypted_path_default
                    logger.info(f"使用默认加密文件作为源: {source_path_to_decrypt}")
                elif potential_inplace_source_path.exists():
                    # 默认 .enc 文件不存在，假设输入路径本身是加密文件 (inplace encrypt)
                    source_path_to_decrypt = potential_inplace_source_path
                    logger.info(f"默认加密文件未找到，假设 {source_path_to_decrypt} 是源文件 (可能由于原地加密)")
                else:
                    logger.error(f"未找到要解密的源文件 (尝试了 {encrypted_path_default} 和 {potential_inplace_source_path})。")
                    error_files.append(f"{filename} (源文件未找到)")
                    continue
                    
                # --- 2. 读取源加密文件内容 ---
                try:
                    with open(source_path_to_decrypt, 'rb') as f:
                        encrypted_bytes = f.read()
                    if not encrypted_bytes:
                        logger.error(f"源加密文件 {source_path_to_decrypt} 为空。")
                        error_files.append(f"{filename} (源文件为空)")
                        continue
                except Exception as read_err:
                    logger.error(f"读取源加密文件 {source_path_to_decrypt} 时出错: {read_err}")
                    error_files.append(f"{filename} (读取源文件失败)")
                    continue

                # --- 3. 解密数据 ---
                decrypted_data = None
                try:
                    # 调用管理器的方法获取完全解密后的数据
                    # 这将处理 JSON 的递归解密、文本和二进制的直接解密
                    decrypted_data = manager.get_decrypted_file_content(filename, encryptor, file_type=args.type)
                    
                    if decrypted_data is None:
                         # get_decrypted_file_content 内部已经记录了错误
                         # 这里直接添加到 error_files 列表
                         error_files.append(f"{filename} (解密或读取失败，详情见日志)")
                         continue
                         
                    logger.debug(f"成功从 {source_path_to_decrypt} 解密数据 (类型: {type(decrypted_data)})")
                    
                except Exception as decrypt_err: # 捕获 get_decrypted_file_content 中未预料的错误
                    logger.error(f"调用 get_decrypted_file_content 时发生意外错误 ({filename}): {decrypt_err}", exc_info=True)
                    error_files.append(f"{filename} (解密过程中发生意外错误)")
                    continue
                    
                # --- 4. 确定目标写入路径 ---
                # 目标路径始终是不带 .enc 的路径
                target_path = manager._get_path(filename, file_type=args.type, encrypted=False)
                if args.inplace:
                    logger.info(f"原地解密，目标路径: {target_path} (将覆盖此文件)")
                else:
                    logger.info(f"解密并保存到目标路径: {target_path}")
                
                # --- 5. 保存解密后的数据到目标路径 ---
                try:
                    target_path.parent.mkdir(parents=True, exist_ok=True) # 确保目标目录存在
                    if args.type == "json":
                        # decrypted_data 已经是 Python 对象
                        with open(target_path, 'w', encoding='utf-8') as f:
                            json.dump(decrypted_data, f, ensure_ascii=False, indent=4)
                    elif args.type == "text":
                        # decrypted_data 是字符串
                        with open(target_path, 'w', encoding='utf-8') as f:
                            f.write(decrypted_data)
                    elif args.type == "binary":
                        # decrypted_data 是字节
                        with open(target_path, 'wb') as f:
                            f.write(decrypted_data)
                    # 添加实际修改的文件路径
                    success_files.append(str(target_path))
                    logger.info(f"成功将解密数据保存到: {target_path}")
                except Exception as write_err:
                    logger.error(f"将解密数据写入 {target_path} 时失败: {write_err}")
                    error_files.append(f"{filename} (写入目标失败)")
                    continue # 跳过清理步骤
                    
                # --- 6. 清理源文件 (如果不是原地操作) ---
                # 清理逻辑：如果源文件是 .enc 文件，并且与目标文件不同，则删除源文件
                # 这适用于非原地解密，也适用于从 .enc 文件进行的原地解密
                if source_path_to_decrypt.exists() and source_path_to_decrypt != target_path:
                    try:
                        source_path_to_decrypt.unlink()
                        logger.info(f"已删除源加密文件: {source_path_to_decrypt}")
                    except OSError as e:
                        logger.error(f"删除源加密文件 {source_path_to_decrypt} 时出错: {e}")
                        # 继续处理，不影响整体成功状态
            except Exception as e:
                # General error catch for the loop iteration
                logger.error(f"处理文件 '{filename}' 时发生意外错误: {e}", exc_info=args.verbose)
                error_files.append(f"{filename} (未知处理错误)")

        message = f"解密操作完成. 成功: {len(success_files)}, 失败: {len(error_files)}."
        result = {
            "status": "success" if not error_files else "partial_error",
            "success_files": success_files,
            "error_files": error_files,
            "message": message
        }
        return result, (1 if error_files else 0)

    except Exception as e:
        logger.error(f"解密文件为明文失败: {e}", exc_info=args.verbose)
        return {"status": "error", "message": f"解密操作失败: {e}"}, 1


def cmd_rotate_key(args, manager: SecureConfigManager):
    """轮换密钥"""
    try:
        current_key = SystemKeychain.get_master_key()
        if not current_key:
            return {"status": "error", "message": "无法获取当前主密钥用于轮换"}, 1

        logger.info("开始密钥轮换... 这可能需要一些时间，取决于配置文件数量和大小。")

        # 1. 生成新密钥
        new_key = SystemKeychain.generate_key()
        new_key_str = new_key.decode('utf-8') if isinstance(new_key, bytes) else new_key
        logger.info(f"已生成新密钥: {new_key_str}")

        # 2. 创建新旧加密器
        try:
             old_encryptor = EnhancedAES256Encryptor(current_key)
             new_encryptor = EnhancedAES256Encryptor(new_key)
        except Exception as e:
             logger.error(f"创建加密器失败: {e}")
             return {"status": "error", "message": f"创建加密器实例失败: {e}"}, 1


        # 3. 遍历所有配置文件，解密并用新密钥重新加密
        configs = manager.list_configs()
        success_files = []
        error_files = []

        for filename in configs:
            logger.debug(f"处理文件: {filename}")
            try:
                # 获取解密后的数据
                decrypted_data = manager.get_decrypted_file_content(filename, old_encryptor)
                if decrypted_data is None:
                    logger.error(f"使用旧密钥解密文件 '{filename}' 失败，跳过。")
                    error_files.append(f"{filename} (旧密钥解密失败)")
                    continue

                # 用新密钥重新加密并保存
                manager.encrypt_and_save_content(filename, decrypted_data, new_encryptor)
                success_files.append(filename)
                logger.debug(f"文件 '{filename}' 密钥轮换成功。")

            except Exception as e:
                logger.error(f"轮换文件 '{filename}' 密钥失败: {e}", exc_info=args.verbose)
                error_files.append(f"{filename} ({e})")

        # 4. 提示用户更新密钥环境变量
        logger.info("密钥轮换过程完成。")
        logger.warning("!!!! 重要 !!!!")
        logger.warning("请立即更新您的 SECURECONFIGMASTERKEY 环境变量为以下新密钥:")
        logger.warning(f"新密钥: {new_key_str}")
        logger.warning("在更新环境变量之前，旧密钥仍然可以访问这些文件，但新创建或修改的文件将使用新密钥。")


        message = f"密钥已轮换. 重新加密成功: {len(success_files)}, 失败: {len(error_files)}."
        result = {
            "status": "success" if not error_files else "partial_error",
            "new_key": new_key_str, # Include new key in output
            "success_files": success_files,
            "error_files": error_files,
            "message": message
        }
        return result, (1 if error_files else 0)

    except Exception as e:
        logger.error(f"密钥轮换失败: {e}", exc_info=args.verbose)
        # Attempt to restore old key if rotation failed midway? Complex.
        # For now, just report the failure.
        return {"status": "error", "message": f"密钥轮换过程中发生严重错误: {e}"}, 1


def cmd_generate_key(args):
    """生成新密钥"""
    try:
        new_key = SystemKeychain.generate_secure_key()
        new_key_str = new_key.decode('utf-8') if isinstance(new_key, bytes) else new_key

        result = {
            "status": "success",
            "new_key": new_key_str,
            "message": "新密钥已生成"
        }

        # Also log to stderr for visibility
        logger.info("新密钥已生成，但未执行密钥轮换。")
        logger.info(f"新密钥: {new_key_str}")

        return result, 0
    except Exception as e:
        logger.error(f"生成密钥失败: {e}", exc_info=args.verbose)
        return {"status": "error", "message": f"生成密钥失败: {e}"}, 1

# --- Main Function ---

def main():
    """主函数，处理命令行参数"""
    parser = argparse.ArgumentParser(
        description="安全配置管理器命令行接口 (SecureConfig CLI)",
        epilog="使用 'secureconfig <command> --help' 查看特定命令的帮助信息。"
    )
    parser.add_argument(
        "-f", "--format",
        choices=["json", "text"],
        default="json",
        help="输出格式 (默认: json)"
    )
    parser.add_argument(
        "-v", "--verbose",
        action="store_true",
        help="显示详细的调试日志信息到 stderr"
    )
    # Add argument for specifying config directory?
    # parser.add_argument("--config-dir", help="Override default configuration directory")

    subparsers = parser.add_subparsers(dest="command", help="可用的子命令", required=True) # Make command required

    # list 命令
    list_parser = subparsers.add_parser("list", help="列出所有配置文件")
    list_parser.add_argument("--type", choices=["json", "text", "binary"], default="json", help="文件类型 (默认: json)")
    list_parser.set_defaults(func=cmd_list_configs)

    # get 命令
    get_parser = subparsers.add_parser("get", help="获取文件内容")
    get_parser.add_argument("name", help="文件名称 (不带扩展名)")
    get_parser.add_argument("--type", choices=["json", "text", "binary"], default="json", help="文件类型 (默认: json)")
    get_parser.add_argument("--raw", action="store_true", help="获取原始加密数据，不进行解密")
    get_parser.set_defaults(func=cmd_get_config)

    # get-value 命令
    get_value_parser = subparsers.add_parser("get-value", help="获取配置中的特定值")
    get_value_parser.add_argument("name", help="配置文件名称")
    get_value_parser.add_argument("key_path", help="键路径，使用点分隔 (例如 'database.password')")
    get_value_parser.set_defaults(func=cmd_get_value)

    # set-value 命令
    set_value_parser = subparsers.add_parser("set-value", help="设置配置中的特定值")
    set_value_parser.add_argument("name", help="配置文件名称")
    set_value_parser.add_argument("key_path", help="键路径 (例如 'database.host')")
    set_value_parser.add_argument("value", help="要设置的值 (字符串、数字、布尔值，或有效的JSON字符串)")
    set_value_parser.set_defaults(func=cmd_set_value)

    # create 命令
    create_parser = subparsers.add_parser("create", help="创建新的文件")
    create_parser.add_argument("name", help="文件名称")
    create_parser.add_argument("--type", choices=["json", "text", "binary"], default="json", help="文件类型 (默认: json)")
    create_parser.add_argument("--template", choices=["empty", "basic"], default="empty",
                            help="使用模板创建 (仅json类型支持basic模板，默认: empty)")
    create_parser.add_argument("--force", action="store_true", help="如果文件已存在，强制覆盖")
    create_parser.set_defaults(func=cmd_create_config)

    # delete 命令
    delete_parser = subparsers.add_parser("delete", help="删除文件")
    delete_parser.add_argument("name", help="要删除的文件名称")
    delete_parser.add_argument("--type", choices=["json", "text", "binary"], default="json", help="文件类型 (默认: json)")
    delete_parser.set_defaults(func=cmd_delete_config)

    # encrypt 命令
    encrypt_parser = subparsers.add_parser("encrypt", help="将指定（或所有）文件内容加密")
    encrypt_parser.add_argument("name", nargs="?", help="要加密的文件名称 (如果省略，则尝试处理所有)")
    encrypt_parser.add_argument("--type", choices=["json", "text", "binary"], default="json", help="文件类型 (默认: json)")
    encrypt_parser.add_argument("--inplace", action="store_true", help="原地加密，不改变文件名 (不添加 .enc 后缀)")
    encrypt_parser.set_defaults(func=cmd_encrypt_plaintext)

    # decrypt 命令
    decrypt_parser = subparsers.add_parser("decrypt", help="解密指定（或所有）文件并用明文覆盖")
    decrypt_parser.add_argument("name", nargs="?", help="要解密的文件名称 (如果省略，则处理所有)")
    decrypt_parser.add_argument("--type", choices=["json", "text", "binary"], default="json", help="文件类型 (默认: json)")
    decrypt_parser.add_argument("--inplace", action="store_true", help="原地解密，不改变文件名 (不移除 .enc 后缀)")
    decrypt_parser.set_defaults(func=cmd_decrypt_to_plaintext)

    # rotate-key 命令
    rotate_key_parser = subparsers.add_parser("rotate-key", help="轮换主密钥并重新加密所有文件")
    rotate_key_parser.set_defaults(func=cmd_rotate_key)

    # generate-key 命令
    generate_key_parser = subparsers.add_parser("generate-key", help="生成一个新的主密钥")
    generate_key_parser.set_defaults(func=cmd_generate_key)

    args = parser.parse_args()

    # 设置日志级别
    if args.verbose:
        logging.getLogger().setLevel(logging.DEBUG)
        logger.debug("详细日志已启用。")
        logger.debug(f"执行命令: {args.command}")
        logger.debug(f"参数: {vars(args)}")


    # 实例化管理器 (可能需要传递 config_dir from args if implemented)
    try:
        manager = SecureConfigManager()
    except Exception as e:
        logger.error(f"初始化 SecureConfigManager 失败: {e}", exc_info=args.verbose)
        output_result({"status": "error", "message": f"初始化管理器失败: {e}"}, args.format)
        return 1 # Exit code for failure

    # 分发命令到对应的函数
    if hasattr(args, 'func'):
        # Pass manager instance to command functions that need it
        if args.command in ["list", "get", "get-value", "set-value", "create", "delete", "encrypt", "decrypt", "rotate-key"]:
            result, exit_code = args.func(args, manager)
        else: # generate-key doesn't need manager
            result, exit_code = args.func(args)

        output_result(result, args.format)
        return exit_code
    else:
        # Should not happen if subparsers are required, but handle defensively
        parser.print_help()
        return 1

if __name__ == "__main__":
    sys.exit(main()) 